package com.qf.dao.impl;

import com.qf.dao.UserDao;
import com.qf.pojo.User;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/*
 *@Description:
 *@author:刘哥
 *@Date:9:43 2022/7/9
 */
public class UserDaoImpl implements UserDao {
    private QueryRunner queryRunner;
    public void setQueryRunner(QueryRunner queryRunner){
        this.queryRunner=queryRunner;
    }
    @Override
    public List<User> selectAll() {
        try {
            return queryRunner.query("select * from t_users",new BeanListHandler<>(User.class));
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void delete(int id) {
        try {
            queryRunner.update("DELETE FROM t_users where id=?",id );
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void update(User user) {
        String sql="update t_users set name=?,password=?,sex=? WHERE id=?";
        Object[] params={user.getName(),user.getPassword(),user.getSex(),user.getId()};
        try {
            queryRunner.update(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void insert(User user) {
        String sql="insert into t_users(name,password,sex,birthday,registTime) values (?,?,?,?,?)";
        Object[] params={user.getName(),user.getPassword(),user.getSex(),user.getBirthday(),user.getRegistTime()};
        try {
            queryRunner.execute(sql,params);
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
